#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Thread.hpp"
#include"InetAddr.hpp"

using namespace ThreadMoudle;

int InitClient()
{
    //创建套接字
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(1);
    }

    return sockfd;
}

void RecvMessage(int sockfd, const std::string& name)
{

    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        InetAddr addr(peer);
        if (n > 0)
        {
            buffer[n] = 0;
            //区分 打印到标准错误里
            std::cerr << buffer << std::endl;
            //消息都是服务端接收的 有服务端发给的客户端 用下面都是127.0.0.1 8888 发的
            //std::cerr << "[" << addr.AddrStr() << "]: " << buffer << std::endl;

        }
        else
        {
            std::cerr << "recvfrom error" << std::endl;
            break;
        }
    }

}


void SenderMessage(int sockfd, std::string severip, uint16_t severport, const std::string& name)
{
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(severport);
    sever.sin_addr.s_addr = inet_addr(severip.c_str());

    std::string cli_prefix = name + "#";  //sender + name# 你好
    while (1)
    {
        std::string line;
        std::cout << cli_prefix;
        std::getline(std::cin, line);

        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&sever, sizeof(sever)); // 发送消息 需要目标
        if(n <= 0)
        {
            std::cout << "udpclient sendmessag error!!!" << std::endl;
            break;
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3) // 参数个数
    {
        std::cerr << "Usage: " << argv[0] << "sever_ip sever_port" << std::endl;
        exit(0);
    }

    std::string sever_ip = argv[1];
    uint16_t sever_port = std::stoi(argv[2]);
    int sockfd = InitClient();

    //线程创建时的回调函数只能有string 一个参数 所以绑定
    Thread recver("recver-thread", std::bind(&RecvMessage, sockfd, std::placeholders::_1));
    Thread sender("sender_thread", std::bind(&SenderMessage, sockfd, sever_ip, sever_port, std::placeholders::_1));

    recver.Start();
    sender.Start();

    recver.Join();
    sender.Join(); 
 


    ::close(sockfd);

    return 0;
}